package Reflect.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: zcw
 * @version: 1.0
 * 演示通过反射调用方法
 */
public class ReflectAccessMethod {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        // 1.得到Boss对应的class对象
        Class<?> bossCls = Class.forName ("Reflect.Test.Boss");
        // 2.创建对象
        Object o = bossCls.newInstance ();
        //3. 调用public的hi方法
        Method hi = bossCls.getMethod ("hi",String.class);
//        Method hi = bossCls.getDeclaredMethod ("hi",String.class);
        //这两个都行，getMethod获取共有的，getDeclaredMethod获取所有的
        hi.invoke (o,"赶紧干活！");
        //4 调用private static 方法
        Method bb = bossCls.getDeclaredMethod ("bb", int.class, String.class, char.class);
        bb.setAccessible (true);
        System.out.println (bb.invoke (null, 5, "小涛禁止狗叫", '!'));
        //在反射中，如果方法有返回值，同意返回Object
    }
}
class Boss{
    public int age;
    private static String name;

    public Boss() {
    }
    private static String bb(int n,String s,char c){
        return n + " " + s + " " + c;
    }
    public void hi(String s){
        System.out.println (s);
    }
}
